package com.andnnl.mongo2;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Created by chenss on 2020/11/5.
 */
@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 3, time = 1, timeUnit = TimeUnit.SECONDS) //预热5次
@Measurement(iterations = 10, time = 5, timeUnit = TimeUnit.SECONDS) //测试10次，每次5秒
@Threads(8) //线程数
@Fork(2)//JMH 会 fork 出两个进程来进行测试。
//@OutputTimeUnit(TimeUnit.MILLISECONDS)
@OutputTimeUnit(TimeUnit.SECONDS) //单位是秒
@State(Scope.Thread)
public class MongoJmhTest2 {
    static Random random = new Random();
    static Mobile2DAO user = new Mobile2DAO();
    //    static long startMobile = 13901010001L;
    static long startMobile = 13801010001L;
//    static long startMobile2 = 13201010001L;

    /**
     * setup初始化容器的时候只执行一次
     */
    @Setup(Level.Trial)
    public void init() {
//        context = SpringApplication.run(Main.class);
//        dataService = context.getBean(DataService.class);
    }

    @Benchmark
    public void testBatchOne() {
        Mobile2Entity e = user.findByMobile(startMobile + random.nextInt(10000000));
    }

    @Benchmark
    public void testBatch200() {
        List<Long> list = new ArrayList<>();
        for (int k = 0; k < 200; k++) {
            list.add(startMobile + random.nextInt(10000000));
        }
        List<Mobile2Entity> rsList = user.findInList(list);
    }

    @Benchmark
    public void testBatch500() {
        List<Long> list = new ArrayList<>();
        for (int k = 0; k < 500; k++) {
            list.add(startMobile + random.nextInt(10000000));
        }
        List<Mobile2Entity> rsList = user.findInList(list);
    }


    private void print(String a) {
    }

    public static void main(String[] args) throws RunnerException {
        Options options = new OptionsBuilder()
                .include(MongoJmhTest2.class.getSimpleName())
                .output("../logs/MongoBenchmark2.log")
                .build();
        new Runner(options).run();
    }
}
